import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

import Reg from '@/views/Reg.vue'
import Login from '@/views/Login.vue'
import Main from '@/views/Main.vue'
import Home from '@/views/Menus/home.vue'
import UserInfo from '../views/Menus/User/info.vue'
import userAvatar from '../views/Menus/User/Avatar.vue'
import UserPwd from '../views/Menus/User/Pwd.vue'
import Cate from '../views/Menus/Article/Cate.vue'
import ArtcleList from '../views/Menus/Article/articleList.vue'

Vue.use(VueRouter)

const routes = [
  // 注册页规则
  { path: '/reg', component: Reg },
  // 登陆页规则
  { path: '/login', component: Login },
  // 后台主页的路由规则
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      { path: 'home', component: Home },
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: userAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: Cate },
      { path: 'art-list', component: ArtcleList }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    const token = store.state.user.token
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
